package com.EAsystem.controller.admin;

import com.EAsystem.annotation.RequireRole;
import com.EAsystem.entity.Evaluation;
import com.EAsystem.entity.Teacher;
import com.EAsystem.service.EvaluationService;
import com.EAsystem.service.TeacherService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
@RequireRole({1}) // 只有管理员可以访问
public class EvaluationController {

    @Autowired
    private EvaluationService evaluationService;
    
    @Autowired
    private TeacherService teacherService;

    /**
     * 评教信息管理页面
     */
    @GetMapping("/online")
    public String evaluationPage(@RequestParam(defaultValue = "1") int page,
                                @RequestParam(defaultValue = "5") int size,
                                @RequestParam(required = false) String teacherName,
                                @RequestParam(required = false) Integer teacherId,
                                Model model) {
        
        PageInfo<Evaluation> pageInfo;

        if (teacherId != null && teacherId > 0) {
            pageInfo = evaluationService.getAllEvaluationsByPage(page, size);
        } else {
            pageInfo = evaluationService.getAllEvaluationsByPage(page, size);
        }

        PageInfo<Teacher> teacherPageInfo = teacherService.findAllByPage(1, 1000); // 获取足够多的教师
        List<Teacher> allTeachers = teacherPageInfo.getList();

        List<Integer> pageNumbers = new ArrayList<>();
        for (int i = 1; i <= pageInfo.getPages(); i++) {
            pageNumbers.add(i);
        }
        
        model.addAttribute("evaluations", pageInfo.getList());
        model.addAttribute("allTeachers", allTeachers);
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("searchTeacherName", teacherName);
        model.addAttribute("searchTeacherId", teacherId);
        model.addAttribute("pageNumbers", pageNumbers);
        
        return "admin/evaluation";
    }

    /**
     * 查看评价详情
     */
    @GetMapping("/online/view/{id}")
    @ResponseBody
    public Map<String, Object> viewEvaluation(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            Evaluation evaluation = evaluationService.getEvaluationById(id);
            if (evaluation != null) {
                result.put("success", true);
                result.put("evaluation", evaluation);
            } else {
                result.put("success", false);
                result.put("message", "评价记录不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取评价信息失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除评价
     */
    @GetMapping("/online/delete/{id}")
    public String deleteEvaluation(@PathVariable Integer id) {
        evaluationService.deleteEvaluationById(id);
        return "redirect:/admin/online";
    }

    /**
     * 批量删除评价
     */
    @GetMapping("/online/batchDelete")
    public String batchDeleteEvaluations(@RequestParam("ids") String ids) {
        if (ids != null && !ids.isEmpty()) {
            for (String id : ids.split(",")) {
                try {
                    evaluationService.deleteEvaluationById(Integer.valueOf(id));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        return "redirect:/admin/online";
    }

    /**
     * 搜索教师（用于AJAX）
     */
    @GetMapping("/online/searchTeacher")
    @ResponseBody
    public Map<String, Object> searchTeacher(@RequestParam String teacherName,
                                           @RequestParam(defaultValue = "1") int page,
                                           @RequestParam(defaultValue = "10") int size) {
        Map<String, Object> result = new HashMap<>();
        try {
            PageInfo<Evaluation> pageInfo = evaluationService.getAllEvaluationsByPage(page, size);

            if (teacherName != null && !teacherName.trim().isEmpty()) {
                pageInfo.getList().removeIf(evaluation -> 
                    evaluation.getTeacher() == null || 
                    evaluation.getTeacher().getUser() == null ||
                    evaluation.getTeacher().getUser().getRealName() == null ||
                    !evaluation.getTeacher().getUser().getRealName().contains(teacherName.trim())
                );
            }
            
            result.put("success", true);
            result.put("evaluations", pageInfo.getList());
            result.put("totalRecords", pageInfo.getTotal());
            result.put("totalPages", pageInfo.getPages());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "搜索失败：" + e.getMessage());
        }
        return result;
    }
} 